<template>
  <div class="api-test-container">
    <div class="test-box">
      <h2>API 连接测试</h2>
      
      <div class="test-section">
        <h3>基础连接测试</h3>
        <button @click="testBasicConnection" :disabled="basicLoading" class="test-btn">
          {{ basicLoading ? '测试中...' : '测试基础连接' }}
        </button>
        <div v-if="basicResult" class="result">
          <pre>{{ basicResult }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h3>登录测试</h3>
        <div class="form-group">
          <label>用户名:</label>
          <input v-model="testForm.username" type="text" placeholder="输入用户名" />
        </div>
        <div class="form-group">
          <label>密码:</label>
          <input v-model="testForm.password" type="password" placeholder="输入密码" />
        </div>
        <button @click="testLogin" :disabled="loginLoading" class="test-btn">
          {{ loginLoading ? '登录中...' : '测试登录' }}
        </button>
        <div v-if="loginResult" class="result">
          <pre>{{ loginResult }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h3>注册测试</h3>
        <button @click="testRegister" :disabled="registerLoading" class="test-btn">
          {{ registerLoading ? '注册中...' : '测试注册' }}
        </button>
        <div v-if="registerResult" class="result">
          <pre>{{ registerResult }}</pre>
        </div>
      </div>

      <div class="test-section">
        <h3>网络诊断</h3>
        <button @click="diagnoseNetwork" :disabled="diagnoseLoading" class="test-btn">
          {{ diagnoseLoading ? '诊断中...' : '网络诊断' }}
        </button>
        <div v-if="diagnoseResult" class="result">
          <pre>{{ diagnoseResult }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { login, register } from '../api/auth'
import axios from 'axios'

const testForm = reactive({
  username: 'testuser',
  password: '123456'
})

const basicLoading = ref(false)
const loginLoading = ref(false)
const registerLoading = ref(false)
const diagnoseLoading = ref(false)

const basicResult = ref('')
const loginResult = ref('')
const registerResult = ref('')
const diagnoseResult = ref('')

// 测试基础连接
async function testBasicConnection() {
  basicLoading.value = true
  basicResult.value = ''
  
  try {
    const response = await axios.get('http://localhost:5113/api/Auth', {
      timeout: 5000,
      headers: {
        'Content-Type': 'application/json'
      }
    })
    basicResult.value = `连接成功!\n状态码: ${response.status}\n响应: ${JSON.stringify(response.data, null, 2)}`
  } catch (error) {
    console.error('基础连接错误:', error)
    basicResult.value = `连接失败!\n错误类型: ${error.name}\n错误信息: ${error.message}\n\n详细错误: ${JSON.stringify(error, null, 2)}`
  } finally {
    basicLoading.value = false
  }
}

// 测试登录
async function testLogin() {
  loginLoading.value = true
  loginResult.value = ''
  
  try {
    const response = await login({
      username: testForm.username,
      password: testForm.password
    })
    loginResult.value = `登录成功!\n响应: ${JSON.stringify(response.data, null, 2)}`
  } catch (error) {
    console.error('登录错误:', error)
    loginResult.value = `登录失败!\n错误信息: ${error.message}\n\n详细错误: ${JSON.stringify(error.response?.data || error, null, 2)}`
  } finally {
    loginLoading.value = false
  }
}

// 测试注册
async function testRegister() {
  registerLoading.value = true
  registerResult.value = ''
  
  try {
    const response = await register({
      username: testForm.username + Date.now(), // 添加时间戳避免重复
      password: testForm.password
    })
    registerResult.value = `注册成功!\n响应: ${JSON.stringify(response.data, null, 2)}`
  } catch (error) {
    console.error('注册错误:', error)
    registerResult.value = `注册失败!\n错误信息: ${error.message}\n\n详细错误: ${JSON.stringify(error.response?.data || error, null, 2)}`
  } finally {
    registerLoading.value = false
  }
}

// 网络诊断
async function diagnoseNetwork() {
  diagnoseLoading.value = true
  diagnoseResult.value = ''
  
  const results = []
  
  try {
    // 测试1: 检查后端是否运行
    results.push('=== 测试1: 检查后端服务状态 ===')
    try {
      const response = await fetch('http://localhost:5113/')
      results.push(`根路径状态: ${response.status} ${response.statusText}`)
    } catch (error) {
      results.push(`根路径错误: ${error.message}`)
    }
    
    // 测试2: 直接HTTP请求到Auth API
    results.push('\n=== 测试2: 直接HTTP请求到Auth API ===')
    try {
      const response = await fetch('http://localhost:5113/api/Auth')
      results.push(`Auth API状态: ${response.status} ${response.statusText}`)
      const text = await response.text()
      results.push(`响应内容: ${text}`)
    } catch (error) {
      results.push(`Auth API错误: ${error.message}`)
    }
    
    // 测试3: 使用axios请求
    results.push('\n=== 测试3: 使用axios请求 ===')
    try {
      const response = await axios.get('http://localhost:5113/api/Auth')
      results.push(`axios状态: ${response.status}`)
      results.push(`响应数据: ${JSON.stringify(response.data, null, 2)}`)
    } catch (error) {
      results.push(`axios错误: ${error.message}`)
      if (error.response) {
        results.push(`响应状态: ${error.response.status}`)
        results.push(`响应数据: ${JSON.stringify(error.response.data, null, 2)}`)
      }
    }
    
    // 测试4: 检查CORS
    results.push('\n=== 测试4: CORS检查 ===')
    try {
      const response = await fetch('http://localhost:5113/api/Auth', {
        method: 'OPTIONS'
      })
      results.push(`OPTIONS请求状态: ${response.status}`)
      results.push(`CORS头: ${response.headers.get('Access-Control-Allow-Origin')}`)
    } catch (error) {
      results.push(`CORS错误: ${error.message}`)
    }
    
    // 测试5: 检查其他可能的路径
    results.push('\n=== 测试5: 检查其他路径 ===')
    const testPaths = ['/api', '/api/health', '/health', '/swagger']
    for (const path of testPaths) {
      try {
        const response = await fetch(`http://localhost:5113${path}`)
        results.push(`${path}: ${response.status}`)
      } catch (error) {
        results.push(`${path}: 错误 - ${error.message}`)
      }
    }
    
  } catch (error) {
    results.push(`诊断错误: ${error.message}`)
  }
  
  diagnoseResult.value = results.join('\n')
  diagnoseLoading.value = false
}
</script>

<style scoped>
.api-test-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.test-box {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.test-box h2 {
  margin-top: 0;
  color: #333;
  text-align: center;
}

.test-section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background-color: #fafafa;
}

.test-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  color: #409eff;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.test-btn {
  background: #409eff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.test-btn:disabled {
  background: #a0cfff;
  cursor: not-allowed;
}

.result {
  margin-top: 15px;
  background: #f5f5f5;
  border-radius: 4px;
  padding: 15px;
}

.result pre {
  background: white;
  padding: 10px;
  border-radius: 4px;
  overflow-x: auto;
  font-size: 12px;
  white-space: pre-wrap;
  margin: 0;
}
</style> 